﻿using AutoMapper;
using Domain.Material_Management;
using Domain.Process_Procedures;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Dto.Factory_Modeling.OutPut;
using MES.Server.API.Dto.Material_Management.OutPut;
using ReturnValue;
using System;

namespace MES.Server.API.Application.Command.Material_Management
{
    public class GetMaterialGroupHander : IRequestHandler<GetMaterialGroupCommand, ApiPaging<GetMaterialGroupOutPut>>
    {
        private readonly IRepository<MaterialGroupModel> materialGroupRepo;
        private readonly IRepository<ProcessFlowModel> processFlowRepo;
        private readonly IMapper mapper;
        public GetMaterialGroupHander(IRepository<MaterialGroupModel> materialGroupRepo, IRepository<ProcessFlowModel> processFlowRepo,IMapper mapper)
        {
            this.materialGroupRepo = materialGroupRepo;
            this.processFlowRepo = processFlowRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 物料群组查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<GetMaterialGroupOutPut>> Handle(GetMaterialGroupCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<GetMaterialGroupOutPut>();
            var materialGroup = materialGroupRepo.GetAll().Where(x => x.IsDel == false);
            var processFlow = processFlowRepo.GetAll().Where(x => x.IsDel == false);
            var linq = from a in materialGroup
                       join b in processFlow on a.ProcessFlowId equals b.Id into ab
                       from b in ab.DefaultIfEmpty()
                       select new GetMaterialGroupOutPut
                       {
                            Id=a.Id,
                            MaterialGroupCode=a.MaterialGroupCode,
                            MaterialGroupName=a.MaterialGroupName,
                            MaterialGroupType=a.MaterialGroupType,
                            MaterialGroupCount = a.MaterialGroupCount,
                            ProcessFlowId=b.Id,
                            FlowName= b.FlowName ?? string.Empty,
                           MaterialGroupDesc =a.MaterialGroupDesc,
                            CreaterPeople=a.CreaterPeople,
                            CreateTime=a.CreateTime,
                           UpdateTime = a.UpdateTime ?? DateTime.Now
                       };
            result.TotalPage = linq.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Totalcount  = linq.Count();
            result.Code = StatusCode.Success;
            return Task.FromResult(result);
        }
    }
}
